﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace BarcodePrinting
{
    public abstract class BarcodePrinter : IDisposable
    {
        private BarTender.Application btapp;

        private IDictionary<string, string> printKeyDicList = new Dictionary<string, string>
        {
            {"CompanyName","公司名称"},
            {"ProjectName","计划名称"},
            {"ProductID","订单号"},
            {"ProductType","产品名称"},
            {"Unit","单位"},
            {"ProductCode","产品编号"},
            {"Width","宽"},
            {"SubtenseOfWidth","宽(短边)"},
            {"Hight","高"},
            {"SubtenseOfHight","高(短边)"},
            {"SpecialShapedName","加工要求"},
            {"Quantity","数量"},
            {"Price","单价"},
            {"Remark","备注"},
            {"LabelName","标签名称"},
            {"Technics","工艺"},
            {"Multiple","标签倍数"},
            {"PrintQuantity","打印次数"}
        };



        public abstract void Print(LabelModel[] labels);

        public virtual void PrintPreview(LabelModel[] labels)
        {
            DoPrint(labels);
        }

        public virtual void Dispose()
        {
            btapp.Quit(BarTender.BtSaveOptions.btSaveChanges);//退出时同退退出BarTender进程
        }

        protected virtual void DoPrint(LabelModel[] labels)
        {
            if (labels == null || labels.Length == 0) return;
            BarTender.Format btformat;
            btapp = new BarTender.Application();
            btformat = btapp.Formats.Open(@"C:\PrintTemplate.btw", false, "");
            btformat.PrintSetup.NumberSerializedLabels = 1;//设置打印份数
            foreach (LabelModel labelModelItem in labels)
            {
                Type t = labelModelItem.GetType();
                PropertyInfo[] pis = t.GetProperties();
                foreach (var pi in pis)
                    SetPrintValue(btformat, pi, labelModelItem);
            }
            btformat.PrintOut(true, true);//第二个参数设置是否跳出打印属性

        }

        private void SetPrintValue(BarTender.Format btformat, PropertyInfo propertyInfo, LabelModel labelModelItem)
        {
            try
            {
                if (!printKeyDicList.ContainsKey(propertyInfo.Name)) return;
                btformat.SetNamedSubStringValue(printKeyDicList[propertyInfo.Name], propertyInfo.GetValue(labelModelItem, null).ToString());

            }
            catch (Exception ex)
            {

            }
        }
    }
}
